package com.css.zfzx.data.common;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

import java.io.*;

/**
 * @Description: data
 * @Author: lhl
 * @CreateDate: 2021/4/25 18:24
 */
public class RemoteCommandUtil {
    private static Connection conn = null;
    /**
     *  登录服务器主机
     * @param ip 主机IP
     * @param userName  用户名
     * @param userPwd   密码
     * @return 登录对象
     */
    public static Connection login(String ip,String userName,String userPwd){
        boolean flg=false;
        Connection conn = null;
        try {
            conn = new Connection(ip);
            conn.connect();//连接
            flg=conn.authenticateWithPassword(userName, userPwd);//认证
            if(flg){
                //System.out.println("连接成功");
                return conn;
            }
        } catch (IOException e) {
            System.out.println("连接失败"+e.getMessage());
            e.printStackTrace();
        }
        return conn;
    }
    /**
     * 远程执行shll脚本或者命令
     * @param cmd 命令
     * @return 返回迁移文件占用内存的大小
     */
    public static String execmd(Connection connection, String cmd) {
        String result = "";
        try {
            if (connection != null) {
                Session session = getSession(connection);// 打开一个会话
                session.execCommand(cmd);
                result = processStdout(session.getStdout(), "utf-8");
                session.close();
            }
        } catch (IOException e) {
            System.out.println("执行命令失败,链接conn:" + connection + ",执行的命令：" + cmd + "  " + e);
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 获取session
     * @param conn
     * @return
     * @throws IOException
     */
    public static Session getSession(Connection conn) throws IOException{
        Session session = conn.openSession();
        return session;
    }
    /**
     *
     * @Title: processStdout
     * @Description: 解析脚本执行的返回结果
     * @param in 输入流对象
     * @param charset 编码
     * @return String 以纯文本的格式返回
     * @throws
     */
    public static String processStdout(InputStream in, String charset){
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line + "\n");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    /**
     * 关闭服务
     */
    public static void closeConn(Connection conn) {
        if (null == conn) {
            return;
        }
        conn.close();
    }
}
